package com.clouddot.baipai.ui.fragment.V;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIV_HomeWorkFragmentComponent;
import com.clouddot.baipai.contract.IHomeWorkFragmentContract;
import com.clouddot.baipai.http.entity.response.getCourseByIdResponse;
import com.clouddot.baipai.http.entity.response.getCourseListResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.HomeWorkFragmentModule;
import com.clouddot.baipai.ui.activity.H_UMainActivity;
import com.clouddot.baipai.ui.activity.V_SMainActivity;
import com.clouddot.baipai.ui.adapter.HomeWorkAdapter;
import com.clouddot.baipai.ui.adapter.homeworkSpinnerAdapter;
import com.clouddot.baipai.util.EscapeUnescapeUtil;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_ONE;
import static com.clouddot.baipai.util.viewUtil.ViewUtil.imageGetter;

/**
 * Created by wxy on 2018/8/23.
 * 横版班牌作业的主页面
 */
public class V_HomeWorkFrgment extends BaseFragment implements IHomeWorkFragmentContract.IView {
    private homeworkSpinnerAdapter getCourseAdapter;
    private HomeWorkAdapter getHomeWorkAdapter;
    private ArrayList<getCourseListResponse> mDataList = new ArrayList<>();
    private List<getCourseByIdResponse.courseInfoByid> EntityList = new ArrayList<>();
    private String currentItem = "";
    private String currentDataType = "";
    private int currentPage = 1;
    private boolean isRunning = false;

    @Inject
    IHomeWorkFragmentContract.IPresenter mPresenter;

    @BindView(R.id.rightRecyler)
    RecyclerView rightRecyler;

    @BindView(R.id.scanCardNum)
    TextView scanCardNum;
    @BindView(R.id.sp_courseName)
    Spinner sp_courseName;

    @BindView(R.id.LoadingR)
    ImageView LoadingR;
    @BindView(R.id.loadingLR)
    RelativeLayout loadingLR;

    @BindView(R.id.homeworkInfo)
    ScrollView homeworkInfo;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.tvContent)
    TextView tvContent;

    @BindView(R.id.no)
    ImageView no;

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.v_fragment_homework, null);
    }

    @Override
    protected void initViews() {
        DaggerIV_HomeWorkFragmentComponent.builder().homeWorkFragmentModule(new HomeWorkFragmentModule(this)).build().inject(this);

        if (!Env.getAppContext().StudentID.isEmpty()) {
            mPresenter.getCourseListByStudentId(Env.getAppContext().StudentID);
        } else {
            mPresenter.getCourseListByClassId(Env.getAppContext().ClassID);
        }
    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(getActivity());
        LoadingR.startAnimation(loadingAnim);
        rightRecyler.addOnScrollListener(H_UMainActivity.listener);
        homeworkInfo.setPivotX(0);

    }
    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            rightRecyler.setVisibility(View.GONE);
            loadingLR.setVisibility(View.VISIBLE);
            homeworkInfo.setVisibility(View.GONE);
            no.setVisibility(View.GONE);
            currentPage = 1;
            currentDataType = "";
            EntityList.clear();
            mDataList.clear();
            if (!Env.getAppContext().StudentID.isEmpty()) {
                mPresenter.getCourseListByStudentId(Env.getAppContext().StudentID);
            } else {
                mPresenter.getCourseListByClassId(Env.getAppContext().ClassID);

            }
        }
    }

    @Override
    protected void loadData() {

    }

    /**
     *
     * @param flag 1 --> 获取课程作业信息
     *             2 --> 获取课程作业列表
     * @param object
     */
    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            refluesCourseInfo(object);
        } else if (flag == 2) {
            refluesCourseList(object);
        }
        isRunning = false;

    }

    @Override
    public void fail(int flag, String errMsg) {
        if(flag == 2) {
            if(getCourseAdapter != null) {
                mDataList.clear();
                getCourseAdapter.notifyDataSetChanged();
            }
            no.setVisibility(View.VISIBLE);
        }
        loadingLR.setVisibility(View.GONE);
        isRunning = false;
        ToastUtil.showToast(getActivity(), errMsg);

    }

    /**
     * 更新班级作业课程列表
     * @param object
     */
    private void refluesCourseList(Object object) {
        ArrayList<getCourseListResponse> response = (ArrayList<getCourseListResponse>) object;
        if (response.isEmpty()) {
            no.setVisibility(View.VISIBLE);
            return;
        }
        mDataList = response;
        mDataList.get(0).flag = true;
        getCourseAdapter = new homeworkSpinnerAdapter(getActivity());
        getCourseAdapter.setDatas(mDataList);
        sp_courseName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                V_SMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                if (!isRunning) {
                    isRunning = true;
                    currentPage = 1;
                    loadingLR.setVisibility(View.VISIBLE);
                    rightRecyler.setVisibility(View.GONE);
                    currentItem = mDataList.get(position).Id;
                    if (currentDataType.equals(currentItem)) EntityList.clear();
                    mPresenter.getCourseHomeWorkById(currentItem, currentPage, 15);
                    ObjectAnimator.ofFloat(homeworkInfo, "scaleX", 1f, 0).setDuration(500).start();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            homeworkInfo.setVisibility(View.GONE);
                        }
                    }, 500);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_courseName.setAdapter(getCourseAdapter);
        currentItem = mDataList.get(0).Id;
        scanCardNum.setText("一共" + mDataList.size() + "门作业课程");
        scanCardNum.setVisibility(View.VISIBLE);
        // mPresenter.getCourseHomeWorkById(currentItem,currentPage,15);
    }

    /**
     * 更新班级作业课程内容
     * @param object
     */
    private void refluesCourseInfo(Object object) {
        getCourseByIdResponse response = (getCourseByIdResponse) object;
        if (response.EntityList.isEmpty()) {
            if (getHomeWorkAdapter != null) {
                getHomeWorkAdapter.loadMoreEnd();
            } else {
                loadingLR.setVisibility(View.GONE);
                rightRecyler.setVisibility(View.VISIBLE);
            }
            return;
        }
        if (!currentDataType.equals(currentItem)) {
            currentDataType = currentItem;
            EntityList = response.EntityList;
            LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
            rightRecyler.setLayoutManager(mLayoutManager);
            rightRecyler.setItemAnimator(new DefaultItemAnimator());
            getHomeWorkAdapter = new HomeWorkAdapter(EntityList);
            getHomeWorkAdapter.setOnClickListener(new HomeWorkAdapter.AdapterItemClickListener() {
                @Override
                public void onClicked(getCourseByIdResponse.courseInfoByid position) {
                    V_SMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                    for (getCourseByIdResponse.courseInfoByid courseInfo : EntityList) {
                        if (position.Id.equals(courseInfo.Id)) {
                            courseInfo.flag = true;
                        } else {
                            courseInfo.flag = false;
                        }
                    }
                    getHomeWorkAdapter.notifyDataSetChanged();
                    time.setText(position.CreateTime);
                    title.setText(position.Title);
                    final String html = EscapeUnescapeUtil.unescape(position.Detail);
                    ThreadPoolFactory.getThread().execute(new Runnable() {
                        @Override
                        public void run() {
                            final Spanned sp = Html.fromHtml(html, imageGetter, null);
                            Message message = new Message();
                            message.what = MSG_ONE;
                            message.obj = sp;
                            handler.sendMessage(message);
                        }
                    });
                    homeworkInfo.setVisibility(View.VISIBLE);
                    ObjectAnimator.ofFloat(homeworkInfo, "scaleX", 0f, 1).setDuration(500).start();
                }

            });

            currentPage++;
            getHomeWorkAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    mPresenter.getCourseHomeWorkById(currentItem, currentPage, 15);
                }
            });

            rightRecyler.setAdapter(getHomeWorkAdapter);
        } else {
            getHomeWorkAdapter.addData(response.EntityList);
            getHomeWorkAdapter.loadMoreComplete();
        }

        loadingLR.setVisibility(View.GONE);
        rightRecyler.setVisibility(View.VISIBLE);
    }

    /**
     * handle机制更新页面
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    tvContent.setText((Spanned) msg.obj);
                    break;
            }
        }
    };

}
